package com.tenement.utils.phonemsg;

import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.tenement.base.constants.SysmConstants.state;

/**
 * 发送手机验证码,阿里云短信服务
 * 
 * @author wk
 *
 */
public class SendPhoneVerifyCodeUtil {

	private static final Log logger = LogFactory.getLog(SendPhoneVerifyCodeUtil.class);

	/**
	 * 发送手机短信通知
	 * 
	 * @param phoneNumber
	 * @param code
	 * @return
	 * @throws ClientException
	 */
	public static SendSmsResponse sendSms(String phoneNumber,String phoneNumberTo, String userName) throws ClientException {

		// 设置超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");// 不必修改
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");// 不必修改

		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）

		// 替换你的AK
		final String accessKeyId = "----------------------";
		final String accessKeySecret = "-------------------------";

		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);

		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);// 不必修改

		// 组装请求参数
		SendSmsRequest request = new SendSmsRequest();// 不必修改
		// 使用POST提交
		request.setMethod(MethodType.POST);
		// 填写接收方的手机号码
		request.setPhoneNumbers(phoneNumberTo);
		// 必填 此处填写已申请的短信签名
		request.setSignName("凯zone");
		//短信通知，模板code
		request.setTemplateCode("SMS_130835782");
		request.setTemplateParam("{\"consignee\":\"" + userName + "\",\"number\":\""+phoneNumber+"\"}");													
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);// 不必修改
		return sendSmsResponse;

	}
	
	/**
	 * 发送手机验证码
	 * 
	 * @param phoneNumber
	 * @param code
	 * @return
	 * @throws ClientException
	 */
	public static SendSmsResponse sendSms2(String phoneNumber, String code) throws ClientException {

		// 设置超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");// 不必修改
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");// 不必修改

		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）

		// 替换你的AK
		final String accessKeyId = "--------------";
		final String accessKeySecret = "--------------------";

		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);

		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);// 不必修改

		// 组装请求参数
		SendSmsRequest request = new SendSmsRequest();// 不必修改
		// 使用POST提交
		request.setMethod(MethodType.POST);
		// 填写接收方的手机号码
		request.setPhoneNumbers(phoneNumber);
		// 必填 此处填写已申请的短信签名
		request.setSignName("凯zone");
		// 必填 此处填写获得的短信验证码模版CODE SMS_130835782
		request.setTemplateCode("SMS_126620522");
		request.setTemplateParam("{\"code\":\"" + code + "\"}");// 笔者的短信模版中有${code}, // 因此此处对应填写验证码												
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);// 不必修改
		return sendSmsResponse;

	}

	/**
	 * 生成六位数的验证码
	 * 
	 * @return
	 */
	public static String productCode(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String code = "";

		Random random = new Random();

		for (int i = 0; i < 6; i++) {

			code += random.nextInt(10);

		}
		// 先移除session中的phoneCode属性
		session.removeAttribute("phoneCode");
		session.setAttribute("phoneCode", code);
		logger.info("生成的手机验证码：【-code-】");
		return code;
	}
	
	//测试
	public static String productCode() {
		String code = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			code += random.nextInt(10);
		}
		logger.info("生成的手机验证码：【-code-】");
		return code;
	}

	/**
	 * 请求状态返回到controller层
	 * 
	 * @param request
	 * @return
	 */
	public static String returnCode(HttpServletRequest request, String phoneNumber) {
		try {
			SendSmsResponse sendSmsResponse = sendSms2(phoneNumber,productCode(request));
			if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				// 请求成功
				logger.info("【请求成功】" + sendSmsResponse);
				return state.Success;
			} else {
				logger.info("【请求失败】" + sendSmsResponse);
				return state.Failed;
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return state.Failed;
	}
	
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		try {//18772306730 18515382761
			SendSmsResponse sendSmsResponse = sendSms2("----------------", productCode());
			sendSms("---------------","phoneNumberTo","李白");
			if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				// 请求成功
				logger.info("【请求成功】" + sendSmsResponse);

			} else {
				logger.info("【请求失败】" + sendSmsResponse);
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
}
